#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import sys

from dws.commons.common import is_intrusive, log
from common.util.check_utils import is_valid_id
from common.common import exter_attack
from dws.backup.backup_factory import BackupFactory
from dws.commons.const import TaskType
from dws.commons.dws_param_parse import DwsParamParse
from dws.commons.job_info import JobInfo
from dws.commons.parse_param import parse_param_with_jsonschema


@exter_attack
def do_exec(backup_type, pid):
    log.info(f"Enter, pid:{pid}")
    param = parse_param_with_jsonschema(pid)

    job_info = JobInfo(pid=pid,
                       job_id=DwsParamParse.get_job_id(param),
                       copy_id=DwsParamParse.get_copy_id(param),
                       type=TaskType.BACKUP.value,
                       sub_job_id=DwsParamParse.get_sub_job_id(param),
                       backup_type=DwsParamParse.get_type(param),
                       cache_path=DwsParamParse.get_cache_path(param),
                       meta_path=DwsParamParse.get_meta_path(param),
                       data_reps=DwsParamParse.get_data_reps(param),
                       usr=DwsParamParse.get_user_name(param),
                       env_path=DwsParamParse.get_env_path(param),
                       metadata_destination=DwsParamParse.get_metadata_destination(param),
                       storage_id=DwsParamParse.get_storage_id(param),
                       storage_esn=DwsParamParse.get_esn(param),
                       storage_type=DwsParamParse.get_storage_type(param),
                       protect_env=DwsParamParse.get_protect_env(param),
                       backup_tool_type=DwsParamParse.get_backup_tool_type(param),
                       res_name=DwsParamParse.get_res_name(param),
                       nodes=DwsParamParse.get_nodes(param),
                       pro_obj_extend_info=DwsParamParse.get_protect_obj_extend_info(param),
                       pro_obj=DwsParamParse.get_protect_obj(param),
                       cluster_agents=DwsParamParse.get_cluster_agents(param),
                       host_agents=DwsParamParse.get_host_agents(param),
                       open_source_delete=DwsParamParse.is_open_source_delete(param),
                       physical_fine_grained=DwsParamParse.is_physical_fine_grained(param))
    log.info(f'{job_info}')

    backup_ins = BackupFactory.get_backup_ins(backup_type, pid)
    call_back_func = {
        "prepare": backup_ins.white_sub_job,
        "backup": backup_ins.sub_job_backup,
        "post": backup_ins.post_sub_job
    }

    sub_job_type = DwsParamParse.get_sub_job_name(param)

    try:
        if not call_back_func.get(sub_job_type)(job_info, is_intrusive(job_info.nodes)):
            raise Exception(f'{sub_job_type} sub backup failed')
    except Exception as err_str:
        log.error(f"{backup_type} failed end with {err_str}, {job_info.log_format()}")
        return False

    log.info(f"{sub_job_type} suc, {job_info.log_format()}")
    return True


if __name__ == '__main__':
    if len(sys.argv) < 4:
        log.error("Param is wrong.")
        sys.exit(1)

    if not is_valid_id(sys.argv[2]):
        log.warn(f"pid is invalid")
        sys.exit(1)
    try:
        do_exec(sys.argv[1], sys.argv[2])
    except Exception as err:
        log.error(f"Err: {err}, pid: {sys.argv[2]}")
        sys.exit(0)

    sys.exit(0)
